﻿//using FieldTools.Business.BaseManage;
using FieldTools.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;

namespace FieldTools.WebApi
{
    /*
==== 签名校验 ====

为保证接口安全，每次请求必带以下header

| header名 | 类型 | 描述 |
| appId | string | 应用Id |
| time | string | 当前日期，格式为：2017-01-01 |
| sign| string | 签名,签名算法如下 |


签名算法示例：
test=appId +“/”+当前日期（例子：2021-01-14）；key=secret；

    public static String hmacShas256(String text, String key) throws Exception {
        SecretKeySpec sk = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        return hmacSha256(text, sk);
    }
   public static String hmacSha256(String text, SecretKeySpec sk) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(sk);
        byte[] rawHmac = mac.doFinal(text.getBytes());
        return new String(Base64.encodeBase64(rawHmac));
    }
    */
    /// <summary>
    /// 校验签名、十分严格
    /// 防抵赖、防伪造、防重复调用
    /// </summary>
    public class CheckSignGCSZHAttribute : BaseActionFilterAsync
    {
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public async override Task OnActionExecuting(ActionExecutingContext filterContext)
        {
            ////判断是否需要签名
            //if (filterContext.ContainsFilter<IgnoreSignAttribute>())
            //    return;
            //var request = filterContext.HttpContext.Request;
            //IServiceProvider serviceProvider = filterContext.HttpContext.RequestServices;
            //IBaseAppSecretBusiness appSecretBus = serviceProvider.GetService<IBaseAppSecretBusiness>();
            //ILogger logger = serviceProvider.GetService<ILogger<CheckSignAttribute>>();
            //var cache = serviceProvider.GetService<IDistributedCache>();

            //string appId = request.Headers["appId"].ToString();
            //if (appId.IsNullOrEmpty())
            //{
            //    ReturnError("缺少header:appId");
            //    return;
            //}

            //string sign = request.Headers["accessToken"].ToString();
            //if (sign.IsNullOrEmpty())
            //{
            //    ReturnError("缺少header:sign");
            //    return;
            //}

            //string appSecret = await appSecretBus.GetAppSecretAsync(appId);
            //if (appSecret.IsNullOrEmpty())
            //{
            //    ReturnError("header:appId无效");
            //    return;
            //}
            //string newSign = $"{appId}/{DateTime.Now.ToString("yyyy-MM-dd")}".ToHMACSHA256String(appSecret); //appId +“/”+当前日期（例子：2021-01-14）
            //if (sign != newSign)
            //{
            //    request.EnableBuffering();
            //    string body = await request.Body.ReadToStringAsync();

            //    string log = $@"sign签名错误!headers:{request.Headers.ToJson()}body:{body}正确sign:{newSign}";
            //    logger.LogError(log);
            //    ReturnError("header:sign签名错误");
            //    return;
            //}

            //void ReturnError(string msg)
            //{
            //    filterContext.Result = Error(msg);
            //}
        }
    }
}